package com.phone.store.service.impl;

import com.phone.store.entity.PhoneCategory;
import com.phone.store.entity.PhoneInfo;
import com.phone.store.entity.PhoneSpecs;
import com.phone.store.enums.ResultEnum;
import com.phone.store.exception.PhoneException;
import com.phone.store.repository.PhoneCategoryRepository;
import com.phone.store.repository.PhoneInfoRepository;
import com.phone.store.repository.PhoneSpecsRepository;
import com.phone.store.service.PhoneService;
import com.phone.store.util.PhoneUtil;
import com.phone.store.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author fangyu
 * @version v1.0.0
 * @date 2020/7/30 9:03 下午
 */
@Slf4j
@Service
public class PhoneServiceImpl implements PhoneService {

    @Autowired
    private PhoneCategoryRepository categoryRepository;

    @Autowired
    private PhoneInfoRepository phoneInfoRepository;

    @Autowired
    private PhoneSpecsRepository phoneSpecsRepository;

    @Override
    public DataVO findDataVO() {
        DataVO dataVO = new DataVO();
        // 类型 -> categories
        List<PhoneCategory> phoneCategories = categoryRepository.findAll();

        List<PhoneCategoryVO> phoneCategoryVOList = phoneCategories
                .stream()
                .map(obj -> new PhoneCategoryVO(obj.getCategoryName(), obj.getCategoryType()))
                .collect(Collectors.toList());

        dataVO.setCategories(phoneCategoryVOList);

        // 手机 -> phones
        // 通过获取第一个类型(第一个类型即选中首页)
        List<PhoneInfo> phoneInfoList = phoneInfoRepository.findAllByCategoryType(phoneCategories.get(0).getCategoryType());

        List<PhoneInfoVO> phoneInfoVOList = phoneInfoList
                .stream()
                .map(obj -> new PhoneInfoVO(
                        obj.getPhoneId(),
                        obj.getPhoneName(),
                        obj.getPhonePrice() + ".00",
                        obj.getPhoneDescription(),
                        PhoneUtil.createTag(obj.getPhoneTag()),
                        obj.getPhoneIcon()
                ))
                .collect(Collectors.toList());
        dataVO.setPhones(phoneInfoVOList);

        return dataVO;
    }

    @Override
    public List<PhoneInfoVO> findByCategoryType(Integer categoryType) {
        List<PhoneInfo> phoneInfoList = phoneInfoRepository.findAllByCategoryType(categoryType);
        return phoneInfoList
                .stream()
                .map(obj -> new PhoneInfoVO(
                        obj.getPhoneId(),
                        obj.getPhoneName(),
                        obj.getPhonePrice() + ".00",
                        obj.getPhoneDescription(),
                        PhoneUtil.createTag(obj.getPhoneTag()),
                        obj.getPhoneIcon()
                ))
                .collect(Collectors.toList());
    }

    @Override
    public SpecsPackageVO findSpecsByPhoneId(Integer phoneId) {
        PhoneInfo phoneInfo = phoneInfoRepository.findById(phoneId).get();
        List<PhoneSpecs> phoneSpecsList = phoneSpecsRepository.findAllByPhoneId(phoneId);

        // 最外层数据
        SpecsPackageVO specsPackageVO = new SpecsPackageVO();

        // sku
        SkuVO skuVO = new SkuVO();

        // sku.tree[]
        List<TreeVO> treeVOList = new ArrayList<>();

        // sku.list[]
        List<PhoneSpecsVO> phoneSpecsVOList = new ArrayList<>();
        List<PhoneSpecsCasVO> phoneSpecsCasVOList = new ArrayList<>();
        PhoneSpecsVO phoneSpecsVO;
        PhoneSpecsCasVO phoneSpecsCasVO;
        for (PhoneSpecs phoneSpecs : phoneSpecsList) {
            phoneSpecsVO = new PhoneSpecsVO();
            phoneSpecsCasVO = new PhoneSpecsCasVO();
            BeanUtils.copyProperties(phoneSpecs, phoneSpecsVO);
            BeanUtils.copyProperties(phoneSpecs, phoneSpecsCasVO);
            phoneSpecsVOList.add(phoneSpecsVO);
            phoneSpecsCasVOList.add(phoneSpecsCasVO);
        }

        TreeVO treeVO = new TreeVO();
        // sku.tree[].v => set
        treeVO.setV(phoneSpecsVOList);
        treeVOList.add(treeVO);

        Integer price = phoneInfo.getPhonePrice().intValue();
        // sku.price => set
        skuVO.setPrice(price + ".00");
        // sku.stock_num => set
        skuVO.setStockNum(phoneInfo.getPhoneStock());
        // sku.tree[] => set
        skuVO.setTree(treeVOList);
        skuVO.setList(phoneSpecsCasVOList);

        // set sku
        specsPackageVO.setSku(skuVO);

        // set goods
        Map<String, String> goods = new HashMap<>();
        goods.put("picture", phoneInfo.getPhoneIcon());
        specsPackageVO.setGoods(goods);


        return specsPackageVO;
    }

    @Override
    public void subStock(Integer specsId, Integer phoneQuantity) {
        PhoneSpecs phoneSpecs = phoneSpecsRepository.findById(specsId).get();
        PhoneInfo phoneInfo = phoneInfoRepository.findById(phoneSpecs.getPhoneId()).get();

        // sku库存
        Integer result = phoneSpecs.getSpecsStock() - phoneQuantity;
        if (result < 0) {
            log.error("【库存操作】库存不足");
            throw new PhoneException(ResultEnum.PHONE_STOCK_ERROR);
        }

        phoneSpecs.setSpecsStock(result);
        phoneSpecsRepository.save(phoneSpecs);

        // spu库存
        result = phoneInfo.getPhoneStock() - phoneQuantity;
        if (result < 0) {
            log.error("【库存操作】库存不足");
            throw new PhoneException(ResultEnum.PHONE_STOCK_ERROR);
        }

        phoneInfo.setPhoneStock(result);
        phoneInfoRepository.save(phoneInfo);
    }
}
